package siteconfig

import (
	"github.com/gogf/gf/database/gdb"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/os/gcache"
	"github.com/gogf/gf/util/gconv"
)

// Fill with you ideas below.
// Entity is the golang structure for table sys_config.
type Entity struct {
	Name  string `orm:"name" json:"name"`
	Value string `orm:"value" json:"value"`
}

//修改页面请求参数
type EditReq struct {
	Sitename       string `p:"sitename"`
	Beian          string `p:"beian"`
	SiteTitle      string `p:"site_title" `
	Keywords       string `p:"keywords"`
	Description    string `p:"description"`
	MailType       string `p:"mail_type"`
	MailSmtpHost   string `p:"mail_smtp_host"`
	MailSmtpPort   string `p:"mail_smtp_port"`
	MailSmtpUser   string `p:"mail_smtp_user"`
	MailSmtpPass   string `p:"mail_smtp_pass"`
	MailVerifyType string `p:"mail_verify_type"`
	MailFrom       string `p:"mail_from"`
	Sitethumb      string `p:"sitethumb"`
	Oldimage       string `p:"oldimage"`
}

//获取所有数据
func SelectList() ([]Entity, error) {
	db, err := gdb.Instance()
	if err != nil {
		return nil, gerror.New("获取数据库连接失败")
	}
	model := db.Model("t_siteconfig")

	var result []Entity
	model.Structs(&result)
	return result, nil
}

func Edit(req *EditReq) error {
	//数据转换
	var configinfo map[string]string
	err := gconv.Scan(req, &configinfo)
	if err != nil {
		return err
	}
	db, err := gdb.Instance()
	if err != nil {
		return gerror.New("获取数据库连接失败")
	}
	for k, v := range configinfo {
		model := db.Model("t_siteconfig")
		model.Update("value=?", "name=?", v, k)
		gcache.Set(k, v, 0) //更新缓存
	}
	return nil
}

//获取值
func GetValueByName(key string) (string, error) {
	db, err := gdb.Instance()
	if err != nil {
		return "", gerror.New("获取数据库连接失败")
	}
	model := db.Model("t_siteconfig")
	record, err := model.FindOne("name=?", key)
	var result Entity
	err = record.Struct(&result)
	if err != nil {
		return "", err
	}
	return result.Value, nil
}
